import logging
from flask import Blueprint, render_template, request, current_app
from app.modules4.order_stats import get_customer_orders, get_customer_orders_by_phone, calculate_performance_stats

app = Blueprint('order_stats', __name__, template_folder='templates')
logger = logging.getLogger(__name__)


@app.route('/order_stats', methods=['GET'])
def index():
    customer_code = request.args.get('customerCode', '')

    orders = []
    stats = None
    error = None

    try:
        if customer_code:
            # 添加DKH前缀
            customer_code = f'DKH{customer_code}'
            logger.info(f'正在查询客户订单，客户编号：{customer_code}')
            orders = get_customer_orders(customer_code)
            if orders:
                stats = calculate_performance_stats(orders)
                logger.info(f'成功获取客户订单数据，订单数量：{len(orders)}')
            else:
                logger.warning(f'未找到客户订单数据，客户编号：{customer_code}')
    except Exception as e:
        error = '查询订单时发生错误，请稍后重试'
        logger.error(f'查询订单失败，客户编号：{customer_code}，错误：{str(e)}', exc_info=True)

    return render_template('index.html',
                           customer_code=customer_code,
                           orders=orders,
                           stats=stats,
                           error=error)


@app.route('/order_stats_md', methods=['GET'])
def index_md():
    """
    门店版本订单统计接口
    自动为客户编码添加MD前缀
    """
    customer_code = request.args.get('customerCode', '')

    orders = []
    stats = None
    error = None

    try:
        if customer_code:
            # 添加MD前缀（门店版本）
            customer_code = f'MD{customer_code}'
            logger.info(f'正在查询门店客户订单，客户编号：{customer_code}')
            orders = get_customer_orders(customer_code)
            if orders:
                stats = calculate_performance_stats(orders)
                logger.info(f'成功获取门店客户订单数据，订单数量：{len(orders)}')
            else:
                logger.warning(f'未找到门店客户订单数据，客户编号：{customer_code}')
    except Exception as e:
        error = '查询门店订单时发生错误，请稍后重试'
        logger.error(f'查询门店订单失败，客户编号：{customer_code}，错误：{str(e)}', exc_info=True)

    return render_template('index.html',
                           customer_code=customer_code,
                           orders=orders,
                           stats=stats,
                           error=error,
                           is_md=True)  # 添加标识，用于模板区分


@app.route('/order_stats_by_phone', methods=['GET'])
def index_by_phone():
    """
    按手机号查询订单统计接口
    支持通过客户手机号查询订单信息
    """
    phone = request.args.get('phone', '')

    orders = []
    stats = None
    error = None

    try:
        if phone:
            logger.info(f'正在按手机号查询客户订单，手机号：{phone}')
            orders = get_customer_orders_by_phone(phone)
            if orders:
                stats = calculate_performance_stats(orders)
                logger.info(f'成功获取客户订单数据，订单数量：{len(orders)}')
            else:
                logger.warning(f'未找到客户订单数据，手机号：{phone}')
    except Exception as e:
        error = '查询订单时发生错误，请稍后重试'
        logger.error(f'按手机号查询订单失败，手机号：{phone}，错误：{str(e)}', exc_info=True)

    return render_template('index.html',
                           phone=phone,
                           orders=orders,
                           stats=stats,
                           error=error,
                           is_phone_query=True)  # 添加标识，用于模板区分
